package com.diandian.backend.member.service;

import com.diandian.backend.member.constant.MemberConstant;
import com.diandian.backend.member.resp.MemberDouyinLifeMemberInfoPageResp;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.backend.member.domain.DouyinLifeMemberLifeMemberInfo;
import com.diandian.backend.member.dto.*;
import com.diandian.backend.member.mapper.DouyinLifeMemberInfoMapper;
import com.diandian.backend.member.resp.DouyinLifeMemberInfoDetailResp;
import com.diandian.base.boot.starter.response.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DouyinLifeMemberInfoService {

    private static final Logger logger = LoggerFactory.getLogger(DouyinLifeMemberInfoService.class);

    @Autowired
    private DouyinLifeMemberInfoMapper douyinLifeMemberInfoMapper;

    @Autowired
    private DouyinLifeMemberInfoChangeRecordService douyinLifeMemberInfoChangeRecordService;

    public PageResult page(MemberDouyinLifeMemberInfoPageParamDTO requestDTO){

        requestDTO.check();
        int pageNum = requestDTO.getPageNum();
        int pageSize = requestDTO.getPageSize();

        // 查询总数
        int totalCount = douyinLifeMemberInfoMapper.getCount(requestDTO);

        // 查询数据集合
        List<DouyinLifeMemberLifeMemberInfo> dataList = douyinLifeMemberInfoMapper.getPage(requestDTO, requestDTO.getPageSize(), (requestDTO.getPageNum() - 1) * requestDTO.getPageSize());

        // 组装数据
        List<MemberDouyinLifeMemberInfoPageResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            dataList.stream().forEach( x ->{
                MemberDouyinLifeMemberInfoPageResp item = new MemberDouyinLifeMemberInfoPageResp();
                item.setId(x.getId());
                item.setBelong(x.getBelong());
                item.setOpenId(x.getOpenId());
                item.setMobile(x.getMobile());
                item.setAccountId(x.getAccountId());
                item.setPoints(x.getPoints());
                item.setLevel(x.getLevel());
                item.setStatus(x.getStatus());
                item.setCreateTime(x.getCreateTime());
                item.setCreateUserId(x.getCreateUserId());
                item.setCreateUserName(x.getCreateUserName());
                item.setUpdateTime(x.getUpdateTime());
                item.setUpdateUserId(x.getUpdateUserId());
                item.setUpdateUserName(x.getUpdateUserName());
                item.setDel(x.getDel());
                respList.add(item);
            });
        }

        return new PageResult(pageNum, pageSize, totalCount, respList);
    }

    public DouyinLifeMemberInfoDetailResp getDetail(DouyinLifeMemberInfoDetailParamDTO param) {

        DouyinLifeMemberLifeMemberInfo dbData = douyinLifeMemberInfoMapper.getDetail(param);
        if(dbData == null){
            return null;
        }

        DouyinLifeMemberInfoDetailResp result = new DouyinLifeMemberInfoDetailResp();
        result.setId(dbData.getId());
        result.setBelong(dbData.getBelong());
        result.setOpenId(dbData.getOpenId());
        result.setMobile(dbData.getMobile());
        result.setAccountId(dbData.getAccountId());
        result.setPoints(dbData.getPoints());
        result.setLevel(dbData.getLevel());
        result.setStatus(dbData.getStatus());
        result.setCreateTime(dbData.getCreateTime());
        result.setCreateUserId(dbData.getCreateUserId());
        result.setCreateUserName(dbData.getCreateUserName());
        result.setUpdateTime(dbData.getUpdateTime());
        result.setUpdateUserId(dbData.getUpdateUserId());
        result.setUpdateUserName(dbData.getUpdateUserName());
        result.setDel(dbData.getDel());
        return result;
    }

    public void updateById(DouyinLifeMemberInfoUpdateByIdParamDTO param) {
        param.check();

        DouyinLifeMemberInfoDetailParamDTO queryDetailDTO = new DouyinLifeMemberInfoDetailParamDTO();
        queryDetailDTO.setId(param.getId());
        queryDetailDTO.setBelong(param.getBelong());
        DouyinLifeMemberLifeMemberInfo dbData = douyinLifeMemberInfoMapper.getDetail(queryDetailDTO);
        if(dbData == null){
            throw new DefaultException("更新的记录不存在");
        }

        douyinLifeMemberInfoMapper.updateById(param);
    }

    /**
     * 同步：有则更新，无则插入
     * 唯一依据：抖音用户的uid
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void sych(DouyinLifeMemberInfoAddParamDTO param) {

        String belong = param.getBelong();

        // 查询是否已存在该会员
        DouyinLifeMemberInfoDetailParamDTO queryDetailDTO = new DouyinLifeMemberInfoDetailParamDTO();
        queryDetailDTO.setAccountId(param.getAccountId());
        queryDetailDTO.setOpenId(param.getOpenId());
        queryDetailDTO.setBelong(belong);
        DouyinLifeMemberInfoDetailResp dbData = getDetail(queryDetailDTO);

        // 不存在，新增
        if(dbData == null){
            logger.info("当前抖音本地生活会员不存在，执行新增操作...");
            param.setDel(0);
            douyinLifeMemberInfoMapper.add(param);
            addRecord(belong, param.getId(), param.getAccountId(), param.getOpenId(), MemberConstant.OPERATION_TYPE_MEMBER_ADD);
            logger.info("抖音本地生活会员新增完成。");
            return;
        }

        // 存在，更新
        logger.info("当前抖音本地生活会员已存在，执行更新操作...");
        Long id = dbData.getId();
        DouyinLifeMemberInfoUpdateByIdParamDTO updateDetailDTO = new DouyinLifeMemberInfoUpdateByIdParamDTO();
        updateDetailDTO.setId(id);
//        updateDetailDTO.setBelong(belong);
        updateDetailDTO.setMobile(param.getMobile());
        updateDetailDTO.setPoints(param.getPoints());
        updateDetailDTO.setLevel(param.getLevel());
        updateDetailDTO.setStatus(param.getStatus());
        updateDetailDTO.setUpdateTime(param.getUpdateTime());
        updateDetailDTO.setUpdateUserId(param.getUpdateUserId());
        updateDetailDTO.setUpdateUserName(param.getUpdateUserName());
        updateById(updateDetailDTO);

        addRecord(belong, id, param.getAccountId(), param.getOpenId(), MemberConstant.OPERATION_TYPE_MEMBER_UPDATE);
        logger.info("抖音本地生活会员更新完成。");
    }

    @Transactional(rollbackFor = Exception.class)
    public void remove(String belong, String accountId, String openId) {

        // 查询是否已存在该会员
        DouyinLifeMemberInfoDetailParamDTO queryDetailDTO = new DouyinLifeMemberInfoDetailParamDTO();
        queryDetailDTO.setAccountId(accountId);
        queryDetailDTO.setOpenId(openId);
        DouyinLifeMemberInfoDetailResp dbData = getDetail(queryDetailDTO);
        if(dbData == null){
            logger.info("不存在此抖音本地生活会员。");
            throw new DefaultException("不存在此会员");
        }

        douyinLifeMemberInfoMapper.remove(accountId, openId);

        addRecord(belong, dbData.getId(), accountId, openId, MemberConstant.OPERATION_TYPE_MEMBER_REMOVE);
        logger.info("抖音本地生活会员移除完成。");
    }

    /**
     * 保存变更记录
     * @param infoId
     * @param accountId
     * @param openId
     * @param type
     */
    private void addRecord(String belong, Long infoId, String accountId, String openId, String type) {
        DouyinLifeMemberInfoChangeAddParamDTO addParamDTO = new DouyinLifeMemberInfoChangeAddParamDTO();
        addParamDTO.setInfoId(infoId);
        addParamDTO.setBelong(belong);
        addParamDTO.setAccountId(accountId);
        addParamDTO.setOpenId(openId);
        addParamDTO.setType(type);
        douyinLifeMemberInfoChangeRecordService.add(addParamDTO);
    }
}
